import 'package:flutter/material.dart';
import 'package:flutter_project01/apis/user.dart';
import 'package:flutter_project01/utils/Emitter.dart';
import 'package:flutter_project01/utils/TokenManager.dart';
import 'package:flutter_project01/utils/toast.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key, required this.updateIndex});
  // 定义函数类型
  final Function(int) updateIndex;
  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];
  // 用户信息
  Map<String, dynamic> userInfo = {
    'id': '',
    'avatar': '',
    'nickName': '',
  };
// 获取用户信息
  _getUserInfo() async {
    final res = await UserApi.getUserInfo();
    print(res);
    setState(() {
      userInfo = res;
    });
  }

// 监听获取个人信息时间
  listenGetUserInfoEvent() {
    eventBus.on<GetUserInfoEvent>().listen((event) {
      // 刷新个人信息数据
      _getUserInfo();
    });
  }

  // 退出登录
  _logout() {
    // 弹窗二次确认
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text('提示'),
              content: Text('确定退出登录吗？'),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Text('取消')),
                TextButton(
                    onPressed: () {
                      // 清空token
                      tokenManager.deleteToken();
                      Navigator.pop(context);
                      userInfo = {};
                      _getUserInfo();
                      // 跳转到首页  index=0
                      widget.updateIndex(0);
                    },
                    child: Text('确认')),
              ],
            ));
  }

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    listenGetUserInfoEvent();
  }

  List<Widget> getTitleChild() {
    return [
      ClipRRect(
        borderRadius: BorderRadius.circular(50.0),
        child: userInfo['avatar'] != null &&
                userInfo['avatar'].toString().isNotEmpty
            ? Image.network(
                userInfo['avatar'].toString(),
                width: 50,
                height: 50,
              )
            : Image.asset(
                'assets/images/avatar_1.jpg',
                width: 50,
                height: 50,
              ),
      ),
      const SizedBox(width: 10),
      Text(
          userInfo['nickName'] != null &&
                  userInfo['nickName'].toString().isNotEmpty
              ? userInfo['nickName'].toString()
              : '用户名',
          style: TextStyle(fontSize: 16, color: Colors.white)),
      const Spacer(),
      const Text(
        '去完善信息',
        style: TextStyle(color: Colors.white),
      ),
      const Icon(
        Icons.arrow_forward_ios,
        color: Colors.white,
        size: 13,
      )
    ];
  }

  List<Widget> getChildren() {
    return menuList
        .map(
          (item) => SizedBox(
            height: 50,
            child: Row(
              children: [
                Row(
                  children: [
                    Image.asset(
                      item['icon'],
                      width: 20,
                      height: 20,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text(
                      item['title'],
                      style: const TextStyle(fontSize: 16),
                    )
                  ],
                ),
                const Spacer(),
                const Icon(
                  Icons.arrow_forward_ios,
                  size: 12,
                  color: Colors.grey,
                )
              ],
            ),
          ),
        )
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                if (tokenManager.getToken().isEmpty) {
                  Navigator.pushNamed(context, '/login');
                } else {
                  Navigator.pushNamed(context, '/profile');
                }
              },
              child: Row(
                children: getTitleChild(),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: getChildren(),
            ),
          ),
          // 退出登录
          Padding(
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                // 退出登录
                _logout();
              },
              child: Text('退出登录'),
            ),
          ),
        ],
      ),
    );
  }
}
